<!-- src/components/MainLayout.vue -->
<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" :class="{ 'menu-collapsed': isMenuCollapsed }">
        <div class="logo left-db">
          <img src="@/assets/vue.svg">
          <span v-if="!isMenuCollapsed" class="know-title">知识管理平台</span>
        </div>
        <!-- 搜索框 -->
        <div style="display: flex; align-items: center; padding: 20px; background-color: var(--el-menu-bg-color);">
          <!-- <el-input v-if="!isMenuCollapsed" placeholder="搜索..." v-model="searchQuery" clearable></el-input> -->

          <!--     @input="handleSearch" 回车触发事件   -->
          <el-input
            v-if="!isMenuCollapsed"
            v-model="searchQuery"
            placeholder="搜索.."
            clearable
            @keyup.enter="handleSearch" 
           
            style="margin-bottom: 15px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
         </el-input>

          <el-icon @click="toggleMenu" style="margin-left: 5px;"><Menu /></el-icon>
        </div>
        <!-- 菜单 -->
        <el-menu :collapse="isMenuCollapsed" :collapse-transition="false" default-active="1">
          <!-- Menu items... -->
          <el-menu-item index="1">
              <el-icon><Stopwatch /></el-icon>
              <template #title><span>我的知识库</span></template>
            </el-menu-item>
            <el-menu-item index="2"  @click="openDialog">
              <el-icon><Plus /></el-icon>
              <template #title><span>管理知识库</span></template>
            </el-menu-item> 
            <el-menu-item index="3">
              <el-icon><Search /></el-icon>
              <template #title><span>搜一搜</span></template>
            </el-menu-item>
            

            <el-menu-item index="6" @click="showLogoutConfirm">
              <el-icon><SwitchButton /></el-icon>
              <template #title><span>退出登录</span></template>
            </el-menu-item>

        </el-menu>

      </el-aside>
      <el-main>
        <el-scrollbar>
          <!-- <router-view></router-view> -->

          <span class="repo-title bold-span">我的知识库</span>
          <div class="repo-list">
            <el-card class="card-container" v-for="(repo, index) in repos" :key="repo.id" style="margin-bottom: 15px;">
              <template #header>
                <div class="card-header">
                  <el-icon color="#409EFC"><Notebook /></el-icon> <span>{{ repo.title }}</span>
                  <el-popover placement="bottom-end" :width="160" trigger="click" v-model:visible="popoverVisibilities[index]">
                    <template #reference>
                      <el-button style="float: right; padding: 3px 0;" type="text">
                        <el-icon><More /></el-icon>
                      </el-button>
                    </template>
                    <el-menu>
                      <el-menu-item index="3">
                        <el-icon><Lock /></el-icon>
                        <span>权限</span>
                      </el-menu-item>
                      <el-menu-item index="4">
                        <el-icon><Edit /></el-icon>
                        <span>重命名</span>
                        </el-menu-item>
                      <el-menu-item @click="deleteRepo(repo.id!)">
                        <el-icon><Delete /></el-icon>
                        <span>删除</span> 
                      </el-menu-item>
                    </el-menu>
                  </el-popover>
                </div>
              </template>
              <div class="repo-desc" @click="enterNote(repo)">{{ repo.description }}</div>
            </el-card>
          </div>
          <!-- <div v-if="hasMore" class="no-more">加载更多</div> -->
          <div v-if="loading" class="loading-more">正在加载...</div>
          <div v-if="!loading && !hasMore" class="no-more">没有更多了</div>
        </el-scrollbar>
      </el-main>
    </el-container>

    <!-- 创建知识库的对话框 -->
    <el-dialog title="创建新的知识库" v-model="dialogVisible" width="30%">
      <el-form :model="form">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="handleCreateRepo">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">

import { ElButton, ElCard, ElDialog, ElForm, ElFormItem, ElIcon, ElInput, ElMenu, ElMenuItem, ElMessageBox, ElNotification, ElPopover, ElScrollbar } from 'element-plus';
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import useMenuToggle from './components/useMenuToggle';
import useRepoDialog from './components/useRepoDialog';
import useRepos from './components/useRepos';
// 1.2 import store
import useUserStore from '@/store/modules/user';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'MainLayout',
  components: {
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElIcon,
    ElMenu,
    ElMenuItem,
    ElScrollbar,
    ElCard,
    ElPopover
  },
  setup() {
    // 使用组合式函数初始化
    const { isMenuCollapsed, toggleMenu } = useMenuToggle();
    const { dialogVisible, form, openDialog, closeDialog, formLabelWidth, resetForm } = useRepoDialog();
    // const { repos, enterNote, popoverVisibilities, addRepo, deleteRepo, handleScroll, loading, hasMore } = useRepos();
    const router = useRouter(); // 在这里定义一次即可
    const {
      repos, 
      enterNote, 
      popoverVisibilities, 
      addRepo, 
      deleteRepo, 
      loading, 
      hasMore,
      handleScroll, // 引入 handleScroll 方
      setSearchKey // 引入 setSearchKey 方法
    } = useRepos();
    const searchQuery = ref('');
    const userStore = useUserStore();


    function handleSearch() {
      setSearchKey(searchQuery.value);
    }

    function handleCreateRepo() {
      if (form.value.title && form.value.description) {
        addRepo({ ...form.value });
        closeDialog();
        resetForm();
      }
    }

    function showLogoutConfirm() {
      ElMessageBox.confirm(
        '确定要退出登录吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        logout();
      }).catch(() => {
        // 用户取消了操作
        ElNotification({
          title: '取消',
          message: '您取消了退出登录的操作。',
          type: 'info'
        });
      });
    }

    function logout() {
         // 清除 token
        userStore.loginOut();
        // 提示用户
        ElNotification({
          title: '成功',
          message: '您已成功退出登录。',
          type: 'success'
        });

        // 跳转到登录页
        router.push({ path: '/login' });
    }

    // 在组件挂载时监听滚动事件，在卸载时移除监听
    onMounted(() => {
      //  https://blog.csdn.net/weixin_50114203/article/details/140876158
      window.addEventListener('scroll', handleScroll,true);
    });

    onUnmounted(() => {
      window.removeEventListener('scroll', handleScroll);
    });

    // function handleScroll() {
    //   alert("sss");
    //   if (loading.value || !hasMore.value) return;

    //   const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    //   const clientHeight = document.documentElement.clientHeight || window.innerHeight;
    //   const scrollHeight = document.documentElement.scrollHeight;

    //   if (scrollTop + clientHeight >= scrollHeight - 50) {
    //     // 这里调用组合式函数中的方法来加载更多数据
    //     // 注意：这里的逻辑已经在 useRepos 中处理，所以不需要额外操作
    //   }
    // }

    return {
      showLogoutConfirm,
      isMenuCollapsed,
      toggleMenu,
      searchQuery,
      dialogVisible,
      form,
      openDialog,
      closeDialog,
      formLabelWidth,
      repos,
      enterNote,
      popoverVisibilities,
      handleSearch,
      handleCreateRepo,
      deleteRepo,
      loading,
      hasMore
    };
  }
});
</script>

<style scoped lang="scss">
.common-layout {
  width: 100%;
  height: 100vh;
}

.el-container {
  height: 100vh;
}

.el-aside {
  background-color: var(--el-menu-bg-color);
  color: #333;
  text-align: left;
  line-height: normal;

  &.menu-collapsed {
    width: 64px !important; // 折叠时宽度
  }

  .el-menu {
    border-right: none;
  }
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: left;
  line-height: normal;
}

.left-db {
  background-color: var(--el-menu-bg-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 25px;
}

.know-title {
  margin-right: 10px;
}

.repo-title {
  padding-left: 20px;
}

.bold-span {
  font-weight: bold;
  font-family: "黑体";
}

.card-container {
  border-radius: 10px;
  width: 300px;
}

.repo-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.repo-desc {
  padding: 40px 10px;
  color: #737479d2;
  font-size: 12px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .repo-list {
    grid-template-columns: 1fr;
  }
}
</style>